package cn.tedu.file;
/**
 * @Author 金帮嘉诚  @Date 2021-06-17 周四 19:47
 */
/*本类用于测试字节输入流*/

import java.io.*;

/**
 * 知识点：
 * InputStream()
 * FileInputStream()
 * BufferedInputStream()
 *
 * 注意流一定要关闭
 * 注意先写try-catch-final结构
 * 注意read()方法调用时就会获取下一个字节，所以输出要用变量来装
 */
public class TestIn {
    public static void main(String[] args) {
        method1();
        method2();
    }

    private static void method2() {
        InputStream in = null;

        try {
//            in=new BufferedInputStream(new FileInputStream(new File("D:\\ready\\2.txt"));
            in = new BufferedInputStream(new FileInputStream("D:\\ready\\2.txt"));

            int b;
            while ((b = in.read()) != -1) {
                System.out.println(b);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void method1() {
        InputStream in = null;

        try {
//            in=new FileInputStream(new File("D:\\ready\\2.txt"));
            in = new FileInputStream("D:\\ready\\2.txt");

            int b;
            while ((b = in.read()) != -1) {/*执行一次返回一个字节，读取不到返回-1*/
                System.out.println(b);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {/*一定会执行到的代码，不论是否有异常*/
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
